package com.kfm.hotel.controller;

import com.kfm.hotel.config.HotelProperties;
import com.kfm.hotel.domain.RoomImage;
import com.kfm.hotel.domain.RoomType;
import com.kfm.hotel.domain.SysUser;
import com.kfm.hotel.service.RoomImageService;
import com.kfm.hotel.util.Constant;
import com.kfm.hotel.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.LocalDateTime;

@RestController
@RequestMapping("/upload")
public class UploadController {
    @Autowired
    private HotelProperties properties;
    @Autowired
    private RoomImageService service;
    //前端
    @GetMapping
    public ModelAndView upload(){
        ModelAndView modelAndView = new ModelAndView("upload");
        return modelAndView;
    }

    //后端接收
    @PostMapping
    public R uploadFile(MultipartFile file,Integer id, HttpSession session) throws IOException {
        //输出文件名
        String filename=file.getOriginalFilename();
        //获取文件名后缀
        String substring = filename.substring(filename.lastIndexOf("."));
        //获取当前日期
        String data = LocalDate.now().toString().replace("-", "");
        //重命名文件
        String savename=data+"-"+System.currentTimeMillis()+substring;

        //判断文件夹是否存在
        File file1 = new File(properties.getUploadPath(),data);
        if(!file1.exists()){
            //文件夹不存在，自己创建文件夹
           file1.mkdirs();
        }
        String name=data+File.separator+savename;
        //保存文件
        //创建Path对象
        Path path = Paths.get(properties.getUploadPath(), name);
        //文件保存地址
        file.transferTo(path);

        //存入数据库
        //1.实例化对象
        RoomImage roomImage = new RoomImage();
        //2.放置姓名
        roomImage.setUrl(name);
        //3.放置类型编号
        roomImage.setRoomType(id);
        //从session中获取id
        SysUser user= (SysUser) session.getAttribute(Constant.LOGIN_USER);
        roomImage.setCreator(user.getId());
        service.save(roomImage);
        return R.ok("上传成功！");
    }



}
